<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
    />
    <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import http from "@/request/request"
import {useRoute, useRouter} from "vue-router";
import {defineExpose} from 'vue'

const router = useRouter()
const route = useRoute()

const props = defineProps({
  neirong:{
    type:String,
    default:"<p>hello</p>",
  },
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = ref('default')
// 内容 HTML
const valueHtml = ref('<p>hello</p>')

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...', MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        // file 即选中的文件
        // 自己实现上传，并得到图片 url alt href
        // 最后插入图片
        const formdata = new FormData()
        formdata.append("file",file)
        http.upload(formdata).then(res => {
          if (res.data.code === 0) {
            const url = res.data.data.url
            const alt = res.data.data.name
            const href = ""
            insertFn(url, alt, href)
          }
        })
      },
    }
  },
}


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const changeHtml = (textHtml) => {
  valueHtml.value = textHtml
}
const getHtml = () => {
  return valueHtml.value
}

// 监听
watch(()=>props.neirong,()=>{
  console.log("触发watch一次")
  valueHtml.value = props.neirong
},)

defineExpose({valueHtml, changeHtml, getHtml})

// 初始化区域
console.log("富文本组件第一次初始化")
valueHtml.value = props.neirong
</script>

<style scoped>

</style>
